var closeTabsToTheLeft = {};

gBrowser.warncloseLeftTab = function (lTabs) {
	var prefsService = Services.prefs;
	var warnOnClose = prefsService.getBoolPref("browser.tabs.warnOnClose");
	var warnOnCloseOtherTabs = prefsService.getBoolPref("browser.tabs.warnOnCloseOtherTabs");
	if (lTabs.length >= 2) {
		var bundle = this.mStringBundle;
		var prompts = Components.classes["@mozilla.org/embedcomp/prompt-service;1"].getService(Components.interfaces.nsIPromptService);
		var check = {value: true};
		var button;
		if (warnOnClose) {
			button = prompts.confirmEx(window, 
				bundle.getString("tabs.closeWarningTitle"), 
				bundle.getFormattedString("tabs.closeWarningMultipleTabs", [lTabs.length]), 
				(prompts.BUTTON_TITLE_IS_STRING * prompts.BUTTON_POS_0) + (prompts.BUTTON_TITLE_CANCEL * prompts.BUTTON_POS_1),
				bundle.getString("tabs.closeButtonMultiple"), 
				null, null, 
				bundle.getString("tabs.closeWarningPromptMe"),
				check);

			if (button === 0) {
				prefsService.setBoolPref("browser.tabs.warnOnClose", check.value);
				return true;
			} else {
				return false;
			}
		} else if (warnOnCloseOtherTabs) {
			button = prompts.confirmEx(window, 
				bundle.getString("tabs.closeWarningTitle"), 
				bundle.getFormattedString("tabs.closeWarningMultipleTabs", [lTabs.length]), 
				(prompts.BUTTON_TITLE_IS_STRING * prompts.BUTTON_POS_0) + (prompts.BUTTON_TITLE_CANCEL * prompts.BUTTON_POS_1),
				bundle.getString("tabs.closeButtonMultiple"), 
				null, null, 
				null,
				check);
			return (button === 0);
		}
	}
	return true;
};

closeTabsToTheLeft.getLeftUnpinnedTabsOf = function _getLeftUnpinnedTabsOf(aTab) {
	var tabs = gBrowser.tabs;
	ret = [];

	for (var i = 0; i < tabs.length - 1; ++i) {
		var t = tabs[i];
		if (t === aTab) {
			break;
		}
		if (t.pinned) {
			continue;
		}
		ret.unshift(t);
	}

	return ret;
};

closeTabsToTheLeft.removeLeftTabsOf = function _removeLeftTabsOf(aTab) {
	var lTabs = closeTabsToTheLeft.getLeftUnpinnedTabsOf(aTab);

	if (gBrowser.warncloseLeftTab(lTabs)) {
		for (var i = lTabs.length - 1; i >= 0; --i) {
			gBrowser.removeTab(lTabs[i], {animate:true});
		}
	}
};

//Set menuitem's state
window.addEventListener("load", function() {
	document.getElementById('tabContextMenu').addEventListener("popupshowing", function(ev) {
		//Must be called after TabContextMenu.updateContextMenu(menupopup)
		if (ev.target !== this) {
			return;
		}

		var lTabs = closeTabsToTheLeft.getLeftUnpinnedTabsOf(TabContextMenu.contextTab);
		document.getElementById("context_closeTabsToTheLeft").disabled = !lTabs.length;
	}, false);
}, false);

